package com.iven.xie.sonwflake.service.impl;

import com.iven.xie.sonwflake.beans.ID;
import com.iven.xie.sonwflake.service.IdConverter;
import com.iven.xie.sonwflake.service.SnowflakeService;
import com.iven.xie.sonwflake.utils.SnowflakeUtils;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author xiezhendong
 * @date 2021/7/29
 */
@Service
public class SnowflakeServiceImpl implements SnowflakeService {

    @Override
    public Date transTime(long time) {
        return new Date(time + SnowflakeUtils.START_TIME);
    }

    @Override
    public ID expId(long id) {
        IdConverter idConverter = new IdConverterImpl();
        return idConverter.convert(id);
    }

    /**
     * 生成ID（线程安全）
     *
     * @return id
     */
    @Override
    public long genId() {
        return SnowflakeUtils.genId();
    }

    /**
     * 根据时间戳和序列号生成ID
     *
     * @param timeStamp 时间戳
     * @param sequence  序列号
     * @return 生成的ID
     */
    @Override
    public long makeId(long timeStamp, long sequence) {
        return makeId(timeStamp, SnowflakeUtils.getWorkId(), sequence);
    }

    /**
     * 根据时间戳、机器ID和序列号生成ID
     *
     * @param timeStamp 时间戳
     * @param worker    机器ID
     * @param sequence  序列号
     * @return 生成的ID
     */
    @Override
    public long makeId(long timeStamp, long worker, long sequence) {
        IdConverter idConverter = new IdConverterImpl();
        return idConverter.convert(new ID(timeStamp, worker, SnowflakeUtils.getDataId(), sequence));
    }
}
